package com.party.mobile.biz.member;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.party.common.utils.DateUtils;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.commune.CMemberInfo;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.order.*;
import com.party.core.model.system.SysConfig;
import com.party.core.service.commune.ICMemberInfoService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.order.IOrderFormService;
import com.party.core.service.order.IOrderFormSubInfoService;
import com.party.core.service.system.ISysConfigService;
import com.party.mobile.biz.order.OrderBizService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @program: party
 * @description: 社群会员购买业务
 * @author: Hua Qunhao
 * @create: 2020-04-10 12:11
 **/
@Service
public class CMemberBuyBizService {
    protected static Logger logger = LoggerFactory.getLogger(CMemberBuyBizService.class);

    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private MemberBizService memberBizService;
    @Autowired
    private IOrderFormService orderFormService;
    @Autowired
    private IOrderFormSubInfoService orderFormSubInfoService;
    @Autowired
    private OrderBizService orderBizService;
    @Autowired
    private ICMemberInfoService memberInfoService;


    public List<Map<String, String>> getCommoditys(String commodityCode) {
        ArrayList<Map<String, String>> prices = Lists.newArrayList();
        SysConfig xzgsConfig = sysConfigService.findByCode("COMMUNITY_MEMBER_PRICES");
        if (xzgsConfig == null || StringUtils.isEmpty(xzgsConfig.getValue())) {
            return null;
        }
        Map<String, Object> responseMap = (Map<String, Object>) JSONObject.parse(xzgsConfig.getValue());
        responseMap.forEach((key, value) -> {
            Map<String, String> price = (Map) value;
            if (StringUtils.isEmpty(commodityCode)) {
                prices.add(price);
            } else {
                if (key.equalsIgnoreCase(commodityCode)) {
                    prices.add(price);
                }
            }
        });
        return prices;
    }

    public String insertOrder(String memberId, Map<String, String> commodity) {

        MemberGroup xingZheGongSheMemberGroup = memberBizService.getXingZheGongSheMemberGroup();
        Member member = memberService.get(memberId);
        Float price = Float.parseFloat(commodity.get("price"));
        String productName = commodity.get("productName");

        OrderForm orderForm = new OrderForm();
        orderForm.setType(OrderType.ORDER_BUY_C_MEMBER.getCode());
        orderForm.setMemberId(member.getId());
        orderForm.setGoodsId(commodity.get("commodityCode"));
        orderForm.setUnit(1);
        orderForm.setLinkman(member.getUsername());
        orderForm.setPhone(member.getMobile());
        orderForm.setStatus(OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
        orderForm.setIsPay(PaymentState.NO_PAY.getCode());
        orderForm.setPayment(price);
        orderForm.setTitle(productName);
        orderForm.setInitiatorId(xingZheGongSheMemberGroup.getId());

        String id = orderFormService.insert(orderForm);


        OrderFormSubInfo formSubInfo = new OrderFormSubInfo();
        formSubInfo.setOrderId(orderForm.getId());
        formSubInfo.setAuthorLogo(member.getLogo());
        formSubInfo.setAuthorName(member.getRealname());
        formSubInfo.setInitiatorLogo(xingZheGongSheMemberGroup.getLogo());
        formSubInfo.setInitiatorName(xingZheGongSheMemberGroup.getRealname());
        orderFormSubInfoService.insert(formSubInfo);

        return id;
    }


    /**
     * 处理支付业务
     *
     * @param orderForm
     * @param object
     * @param paymentWay
     */
    public void updatePayBusiness(OrderForm orderForm, Object object, Integer paymentWay) throws Exception {
        try {
            orderBizService.updateOrderStatus(orderForm, object, paymentWay);
        } catch (Exception e) {
            logger.error("支付回调异常", e.getMessage());
            throw e;
        }
        String memberId = orderForm.getMemberId();
        String goodsId = orderForm.getGoodsId();

        List<Map<String, String>> commoditys = this.getCommoditys(goodsId);
        if (null == commoditys || commoditys.size() == 0) {
            throw new BusinessException("支付回调异常,商品不存在");
        }
        Map<String, String> commodity = commoditys.get(0);
        int days = Integer.parseInt(commodity.get("days"));

        CMemberInfo memberInfo = memberInfoService.getByMemberId(memberId);
        if(null == memberInfo){
            memberInfo.setMemberId(memberId);
            memberInfo.setMemberGrade(CMemberInfo.MEMBER_GRADE_PAY);
            memberInfo.setCheckStatus(CMemberInfo.CHECK_STATUS_ADOPT);
            memberInfo.setPayTime(new Date());
            memberInfo.setEffectiveTime(DateUtils.addDay(new Date(),days));
            memberInfoService.insert(memberInfo);
        }else{
            Date effectiveTime_old = new Date() ;
            if(null!=memberInfo.getEffectiveTime()){
                effectiveTime_old = memberInfo.getEffectiveTime();
            }
            if(CMemberInfo.MEMBER_GRADE_ORDINARY==memberInfo.getMemberGrade()){
                memberInfo.setPayTime(new Date());
            }
            memberInfo.setEffectiveTime(DateUtils.addDay(effectiveTime_old,days));
            memberInfo.setMemberGrade(CMemberInfo.MEMBER_GRADE_PAY);
            memberInfoService.update(memberInfo);
        }
    }
}
